package threads;

import java.net.InetSocketAddress;
import java.util.Properties;

import server.ServerData;
import utils.PropertiesUtils;
import connection.TCPSecureServerSocket;
import connection.TCPServerSocket;

public class ConnectionInitiatorThread extends Thread {

	private TCPServerSocket _serverSocket;
	private ServerData _serverData;
	private InetSocketAddress _vericopAddress;
	private InetSocketAddress _webServerAddress;

	public ConnectionInitiatorThread() {
		_serverData = ServerData.getServerData();
		_serverSocket = new TCPServerSocket(_serverData);

		Properties certcopProperties = PropertiesUtils.getPropertiesFromFile("config/CERTCOPServer.properties");

		String vericopIp = certcopProperties.getProperty("vericopIp");
		int vericopPort = Integer.parseInt(certcopProperties.getProperty("vericopPort"));
		_vericopAddress = new InetSocketAddress(vericopIp, vericopPort);

		String webServerIp = certcopProperties.getProperty("webServerIp");
		int webServerPort = Integer.parseInt(certcopProperties.getProperty("webServerPort"));
		_webServerAddress = new InetSocketAddress(webServerIp, webServerPort);
	}

	public void run(){
		System.out.println("Thread Initialized");
		while(_serverData.isOnline()){
			TCPSecureServerSocket socket = _serverSocket.connect();

			if(socket == null)
				continue;

			InetSocketAddress socketAddress = socket.getSocketAddress();

			if(socketAddress.equals(_vericopAddress)){
				CertcopVericopConnection vericop = new CertcopVericopConnection(socket);
				_serverData.setVericop(vericop);
				vericop.start();
			}else if(socketAddress.equals(_webServerAddress)){
				CertcopWebConnectionThread web = new CertcopWebConnectionThread(socket);
				web.start();
			}else{			
				CertcopClientThread client = new CertcopClientThread(socket);
				client.start();
			}
		}
	}
}
